Ext.ns('cn.hls.web.action.biz.shipOrder');
var listView = cn.hls.web.action.biz.shipOrder.listView;
var url = cfg.cxt + "/shipOrder/info.action?id=";
listView = function() {
	var store, grid, win, iframe,gpsWin,gpsIframe,printWin,printIframe;
	var sm = new Ext.grid.CheckboxSelectionModel({
		singleSelect : false  //单选设置为false　表示允许多选
	});
	var fields = [ "id",// 编号
	"shipper",//电子运单
	"shipTime",//托运日期
	"loadGoodsTime",//装货时间
	"unloadGoodsTime",//卸货时间
	"car",//车辆信息
	"driverName",//驾驶员
	"escortName"//押运员
	];
	return {
		init : function() {
			  //------------------------------------------------- store
            store = this.createStore();
            //查询条件
			store.on('beforeload', function() {
				if(queryRole){
					this.baseParams = {
						"driverName": Ext.getCmp('shipOrder_driverName').getValue(),
						"escortName": Ext.getCmp('shipOrder_escortName').getValue(),
						"car.licenseNum" : Ext.getCmp('shipOrder_licenseNum').getValue(),
						"car.licenseNum2":Ext.getCmp('shipOrder_licenseNum2').getValue(),
						'beginShipTime':Ext.getCmp('ship_beginTime').getValue(),
						'endShipTime':Ext.getCmp('ship_endTime').getValue(),
						'companyId':companyId==''?undefined:companyId
					};
				}else{
					this.baseParams = {
						'companyId':companyId==''?undefined:companyId
					};
				}
			});
            
			//------------------------------------------------- grid
			grid = this.createGrid();
			if(editRole){
				grid.on('rowdblclick', function(g, r, e) {
					listView.editInit();
				});
			}
			grid.on('render', function(grid) {  
			    var store = grid.getStore();  // Capture the Store.  
			    var view = grid.getView();    // Capture the GridView.  
			    grid.tip = new Ext.ToolTip({  
			        target: view.mainBody,    // The overall target element.  
			        //delegate: '.x-grid3-row', // Each grid row causes its own seperate show and hide.  
			        delegate: '.x-grid3-cell',
			        trackMouse: true,         // Moving within the row should not hide the tip.  
			        renderTo: document.body,  // Render immediately so that tip.body can be  
			        anchor: 'top',                           //  referenced prior to the first show.  
			        listeners: {              // Change content dynamically depending on which element  
			                                  //  triggered the show.  
			            beforeshow: function updateTipBody(tip) {  
			            	var rowIndex = view.findRowIndex(tip.triggerElement);  
	                        var cellIndex = view.findCellIndex(tip.triggerElement);  
			                var cellIndex = view.findCellIndex(tip.triggerElement);
			                if(cellIndex>1){
				                var cell = view.getCell(rowIndex, cellIndex);  
		                        tip.body.dom.innerHTML = cell.innerHTML;  
			                }else{
			                	return false;
			                }
			            }  
			        }  
			    });  
			}); 
			
			// ------------------------------------------------- viewport
			new Ext.Viewport({ 
			      layout : 'fit',
				  items : [grid]
			});
			this.queryResItem();
		},		/**获取查询参数**/
		createStore : function() {
			return new ExtStore({
				url : '/shipOrder/list.action',
				fields : fields
			});
		},
	
		createGrid : function() {
			return new ExtGrid({
				store : store,
				title : '<div class="panelTitleCss">电子运单基本信息列表</div>',
				sm : sm,
				columnLines : true,
				columns : listView.createColumns(),
				tbar : listView.createQueryTbar(),
				bbar : {
					id : 'page',
					xtype : 'pageinfobar',
					pageSize : 20,
					store : store,
					pageMethod : listView.queryResItem
				}
			});
		},
		createColumns : function() {
			var cols = [
					new Ext.grid.RowNumberer(),
					sm,
					{
						sortable : true,dataIndex : 'shipTime',width : 80,autoWidth : true,header : '托运时间',align : 'center',
						renderer : function(value) {
							if (value != null) {
								return new Date(value).dateFormat('Y-m-d');
							} else {
								return '';
							}
						}
					},{
						sortable : true,dataIndex : "shipper",header:'电子运单(托运企业)',align:'center',width : 100,autoWidth : true,
						renderer : function(value) {
							if(value!=null){
								return value.company.name;
							}else{
								return '';
							}
						}
					},
					/*
					{
						sortable : true,dataIndex : 'sendContractor',width : 80,autoWidth : true,header : '发货联系人',align : 'center'
					},
					{
						sortable : true,dataIndex : 'sendContractPhone',autoWidth : true,align : 'center',width:75,header : '发货联系电话',align : 'center'
					},{
						sortable : true,dataIndex : 'receiveContractor',width : 80,autoWidth : true,header : '收货联系人',align : 'center'
					},
					{
						sortable : true,dataIndex : 'receiveContractPhone',autoWidth : true,align : 'center',width:75,header : '收货联系电话',align : 'center'
					},
					{
						sortable : true,dataIndex : "sendAddress",header : '发货地址',autoWidth : true,align : 'center',width : 100
					},
					{
						sortable : true,dataIndex : "loadAddress",header : '装货地址',autoWidth : true,align : 'center',width : 90
					},*/
					{
						sortable : true,dataIndex : "loadGoodsTime",header : '装货时间',autoWidth : true,align : 'center',width : 90,
						renderer : function(value) {
							if (value != null) {
								return new Date(value).dateFormat('Y-m-d  H:i:s');
							} else {
								return '';
							}
						}
					},
					/*{
						sortable : true,dataIndex : "receiveAddress",header : '收货地址',autoWidth : true,align : 'center',width : 100
					},
					{
						sortable : true,dataIndex : "unloadAddress",header : '卸货地址',autoWidth : true,align : 'center',width : 80
					},*/
					{
						sortable : true,dataIndex : "unloadGoodsTime",header : '卸货时间',autoWidth : true,align : 'center',width : 90,
						renderer : function(value) {
							if (value != null) {
								return new Date(value).dateFormat('Y-m-d  H:i:s');
							} else {
								return '';
							}
						}
					},
					{
						sortable : true,dataIndex : "car",header : '车牌号',autoWidth : true,align : 'center',width : 60,
						renderer : function(value) {
							if(value!=null){
								return value.licenseNum;
							}else{
								return '';
							}
						}
					},
					{
						sortable : true,dataIndex : "car",header : '挂车号',autoWidth : true,align : 'center',width : 60,
						renderer : function(value) {
							if(value!=null){
								return value.licenseNum2;
							}else{
								return '';
							}
						}
					},{
						sortable : true,dataIndex : "driverName",header : '驾驶员',autoWidth : true,align : 'center',width : 60
					},{
						sortable : true,dataIndex : "escortName",header : '押运员',autoWidth : true,align : 'center',width : 60
					},{
					    header:'<div style=text-align:center;">操作</div>',
					    autoWidth:true,
					    align:'center',
					    width:120,
						renderer : function(v, c, r) {
							var carNum=r.data.car.licenseNum;
							var s= '<a href="javascript:void(0);"  onclick="listView.viewCarGps(\''+carNum+'\');">【车辆定位】</a>';
							return s;
						}
					}
			];
			return cols;
		},
		createQueryTbar : function() {
			if (queryRole) {// 查询权限
				tbarOpr.push('->');
			 
				tbarOpr.push({
					xtype : "textfield",
					width : 100,
					id : 'shipOrder_driverName',
					name : 'driverName',
					emptyText : '请输入驾驶员',
					style : 'margin-left:10px;',
					enableKeyEvents : true,
					listeners : {
						specialkey : function(field, e) {
							if (e.getKey() == Ext.EventObject.ENTER) {
								listView.queryResItem();
							}
						}
					}
				});
				
				tbarOpr.push({
					xtype : "textfield",
					width : 100,
					id : 'shipOrder_escortName',
					name : 'escortName',
					emptyText : '请输入押运员',
					style : 'margin-left:10px;',
					enableKeyEvents : true,
					listeners : {
						specialkey : function(field, e) {
							if (e.getKey() == Ext.EventObject.ENTER) {
								listView.queryResItem();
							}
						}
					}
				});
				
				tbarOpr.push('-');
				tbarOpr.push({
					xtype : "textfield",
					width : 100,
					id : 'shipOrder_licenseNum',
					name : 'licenseNum',
					emptyText : '请输入车牌号',
					style : 'margin-left:10px;',
					enableKeyEvents : true,
					listeners : {
						specialkey : function(field, e) {
							if (e.getKey() == Ext.EventObject.ENTER) {
								listView.queryResItem();
							}
						}
					}
				});
				
				tbarOpr.push({
					xtype : "textfield",
					width : 100,
					id : 'shipOrder_licenseNum2',
					name : 'licenseNum2',
					emptyText : '请输入挂车号',
					style : 'margin-left:10px;',
					enableKeyEvents : true,
					listeners : {
						specialkey : function(field, e) {
							if (e.getKey() == Ext.EventObject.ENTER) {
								listView.queryResItem();
							}
						}
					}
				});
				tbarOpr.push('-');
				tbarOpr.push({xtype : "label",text : "运单日期"});  
				tbarOpr.push({xtype:"ResetDateField",editable : false,format:"Y-m-d",width:95,id:'ship_beginTime',emptyText:'开始时间',style : 'margin-left:10px;',
					listeners : {
						specialkey : function(field, e) {
							if (e.getKey() == Ext.EventObject.ENTER) {
								listView.queryResItem();
							}
						}
					}
				});  
				tbarOpr.push({xtype:"ResetDateField",editable : false,format:"Y-m-d",width:95,id:'ship_endTime',emptyText:'结束时间',style : 'margin-left:10px;',
						listeners : {
							specialkey : function(field, e) {
								if (e.getKey() == Ext.EventObject.ENTER) {
									listView.queryResItem();
								}
							}
						}
					});  
			　
				tbarOpr.push('-');
				tbarOpr.push({
					text : '查询',
					iconCls : 'mainContent',
					handler : function() {
						listView.queryResItem();
					}
				});

				tbarOpr.push({
					text : '刷新',
					iconCls : 'arrow_refreshIcon',
					handler : function() {
						store.reload();
					}
				});
			}
			return tbarOpr;
		},
		

		queryResItem : function(v) {
			var ptool = Ext.getCmp('page');
			if (!v) {
				v = ptool.pageSize;
			}
			store.load({
				params : {
					"start" : 0,
					"limit" : v
				}
			});

		},
		addInit : function(flag) {
			this.onAddOrEditInit(undefined,false,flag);
			win.show();
			win.setTitle('<div style="text-align:center;">新增电子运单基本信息</div>');
			Ext.getCmp('btnSave').setVisible(true);
		},

		
		editInit : function() {
			var sm = grid.getSelectionModel();
			if(sm.getCount() == 0){
				Ext.Mytip.msg('提示', '请先选择要修改的记录!');
				return;
			}
			
			if(sm.getCount() > 1){
				Ext.Mytip.msg('提示', '请选择一条修改的记录!');
				return;
			}
			var record = sm.getSelected();
			this.onAddOrEditInit(record.data.id,false);
			win.show();
			win.setTitle('<div style="text-align:center;">修改电子运单基本信息</div>');
			Ext.getCmp('btnSave').setVisible(true);
		},
		show : function() {
			var sm = grid.getSelectionModel();
			if(sm.getCount() == 0){
				Ext.Mytip.msg('提示', '请先选择要查看的记录!');
				return;
			}
			
			if(sm.getCount() > 1){
				Ext.Mytip.msg('提示', '请选择一条查看的记录!');
				return;
			}
			var record = sm.getSelected();
			this.onAddOrEditInit(record.data.id,true);
			win.show();
			win.setTitle('<div style="text-align:center;">查看电子运单基本信息</div>');
			Ext.getCmp('btnSave').setVisible(false);
		},
		/**编辑或新增操作**/
		/**
		 * @param id 编号
		 * @param isShow 是否查看
		 * @param  isInputAdd 是否通过文本框输入的方式新增数据
		 */
		onAddOrEditInit : function(id,isShow,isInputAdd) {
			if(!win){
				win = this.createWindow(id,isShow,isInputAdd);
			} else {
				var temp_url;
				if(id!=undefined&& id!=''&& id!=null){
					temp_url=url+id;
				}else{
					temp_url=url;
				}
				if(isShow){
					temp_url+='&show=true';
				}
				if(isInputAdd){//通过文本框输入的方式新增数据
					temp_url+='&flag=true';
				}
				document.getElementById("iframe").src=temp_url;
			}
		},
		/**打印承运方窗口**/
		printCarrier:function(){
			var url=cfg.cxt+'/shipOrder/carryView.action';
			this.openPrintDialog(url,'承运方基本信息');
		},
		/**打印托运方窗口**/
		printShipper:function(){
			var url=cfg.cxt+'/shipOrder/shipperView.action';
			this.openPrintDialog(url,'托运方基本信息');
		},
		/**打印收货方窗口**/
		printReceiver:function(){
			var url=cfg.cxt+'/shipOrder/receiverView.action';
			this.openPrintDialog(url,'收货方基本信息');
		},
		/**打开打印窗口**/
		openPrintDialog:function(url,title){
			var sm = grid.getSelectionModel();
			if(sm.getCount() == 0){
				Ext.Mytip.msg('提示', '请先选择要查看的记录!');
				return;
			}
			
			if(sm.getCount() > 1){
				Ext.Mytip.msg('提示', '请选择一条查看的记录!');
				return;
			}
			//获取选中记录的编号
			var record = sm.getSelected();
			url=url+'?id='+record.data.id;
			if(!printWin){
				printWin=this.createPrintWindow(url,title);
			}else{
				document.getElementById("printIframe").src=url;
			}
			printWin.setTitle('<div style="text-align:center;">'+title+'</div>');
			printWin.show();
		},
		/**创建printWindow窗口**/
		createPrintWindow:function(url,title){
			return new ExtWin({
			    width : 1024,
				height : 560,
				maximizable: true,
				title:'<center>'+title+'</center>',
				items : [{
					xtype : 'panel',
					html  : '<iframe id="printIframe" src=' + url+ ' scrolling="auto" frameborder="0" width="100%" height="100%"></iframe>'
				}],
				buttons : [{
					text : '打印',
					id:"btnPrint",
					iconCls : 'printerIcon',
					handler : function() {
						printIframe = document.getElementById("printIframe").contentWindow;
						listView.printForm();
					}
				},{
					text : '关闭',
					iconCls : 'deleteIcon',
					handler : function() {
						printWin.hide();
					}
				}]
			});
		},
		//打印页面内容
		printForm:function(){
			var myFrame=window.frames[0];
			var obj=myFrame.$("#table_form_div");
			obj.jqprint({importCSS:true,printContainer:true,operaSupport:true});
		},
		subForm : function() {
			var myFrame=window.frames[0];
			if(myFrame.allow_save){
				//发货人省份信息
				var sendProvinceName=myFrame.$("#sendProvince").find("option:selected").text();
				var sendCityName=myFrame.$("#sendCity").find("option:selected").text();
				var sendAreaName=myFrame.$("#sendArea").find("option:selected").text();
				myFrame.$("#sendProvinceName").val(sendProvinceName);
				myFrame.$("#sendCityName").val(sendCityName);
				myFrame.$("#sendAreaName").val(sendAreaName);
				//收货人省份信息
				var receiveProvinceName=myFrame.$("#receiveProvince").find("option:selected").text();
				var receiveCityName=myFrame.$("#receiveCity").find("option:selected").text();
				var receiveAreaName=myFrame.$("#receiveArea").find("option:selected").text();
				myFrame.$("#receiveProvinceName").val(receiveProvinceName);
				myFrame.$("#receiveCityName").val(receiveCityName);
				myFrame.$("#receiveAreaName").val(receiveAreaName);
				$('#subBtn', iframe.document).click();
			}else{
				Ext.Mytip.msg('提示', '存在相同的货物信息!');
				return;
			}
		},

		tip : function(text) {
			Ext.Mytip.msg('提示', text);
		},

		closeWindow : function() {
			win.hide();
		},
		/**
		 * 显示窗口
		 */
		createWindow : function(id,isShow,isInputAdd) {
			var frame_url;
			if(id!=undefined && id!=''&& id!=null){
				frame_url=url+id;
			}else{
				frame_url=url;
			}
			if(isShow){
				frame_url+='&show=true';
			}
			if(isInputAdd){
				frame_url+='&flag=true';
			}
			return new ExtWin({
			    width : 1024,
				height : 650,
				maximizable: true,
				items : [{
					xtype : 'panel',
					html  : '<iframe id="iframe" src=' + frame_url+ ' scrolling="auto" frameborder="0" width="100%" height="100%"></iframe>'
				}],
				buttons : [{
					text : '保存',
					id:"btnSave",
					iconCls : 'acceptIcon',
					handler : function() {
						iframe = document.getElementById("iframe").contentWindow;
						listView.subForm();
					}
				},{
					text : '关闭',
					iconCls : 'deleteIcon',
					handler : function() {
						win.hide();
					}
				}]
			});
		},
		/**查看车辆运行轨迹**/
		viewCarGps:function(cardNum){
			var frame_url='http://122.227.217.62:9999/gps/GetPositionHLKJ?'+cardNum+',800,600,18';
			if(!gpsWin){
				gpsWin = this.createGpsWindow(frame_url);
			} else{
				document.getElementById("gpsIframe").src=frame_url;
			}
			gpsWin.show();
		},
		/**创建gpsWindow窗口**/
		createGpsWindow:function(url){
			return new ExtWin({
			    width : 800,
				height : 650,
				maximizable: true,
				title:'<center>车辆定位</center>',
				items : [{
					xtype : 'panel',
					html  : '<iframe id="gpsIframe" src=' + url+ ' scrolling="auto" frameborder="0" width="100%" height="100%"></iframe>'
				}],
				buttons : [{
					text : '关闭',
					iconCls : 'deleteIcon',
					handler : function() {
						gpsWin.hide();
					}
				}]
			});
		},
		
		deleteItem : function() {
			var sm = grid.getSelectionModel();
			if (sm.getCount() == 0) {
				Ext.Mytip.msg('提示', '您尚未选择要删除的记记录！');
				return;
			}
			var ids = [];
			sm.each(function(r) {
				ids.push(r.data.id);
			});

			Ext.Msg.confirm('请确认',
					'<span style="color:red"><b>提示：</b>确定删除吗？</span>',
					function(btn, text) {
						if (btn == 'yes') {
							Ext.Ajax.request({
								url : cfg.cxt + '/shipOrder/del.action',
								success : function(response) {
									var rt = Ext.decode(response.responseText);
									if (rt.success) {
										// listView.queryResItem();
										store.reload();
										Ext.Mytip.msg('提示', '删除成功！');
									} else {
										bangni.ajaxError(response);
									}
								},
								failure : bangni.ajaxError,
								params : {
									"ids" : ids.join(',')
								}
							});
						}
					});
		}
	}
}();
Ext.onReady(listView.init, listView);